package com.shigen.demo.atguigu;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 信号量
 *
 * @author shigenfu
 * @date 2022/5/22 7:27 下午
 */
public class SemaphoreDemo {

  public static void main(String[] args) {
    // 模拟三个停车位
    Semaphore semaphore = new Semaphore(3);
    for (int i = 0; i < 6; i++) {
      new Thread(() -> {
        try {
          semaphore.acquire();
          System.out.println(Thread.currentThread().getName() + "  获得车位");
          TimeUnit.SECONDS.sleep(3);
          System.out.println(Thread.currentThread().getName() + "  离开");
        } catch (Exception e) {
          e.printStackTrace();
        } finally {
          semaphore.release();
        }
      }, String.valueOf(i)).start();
    }

  }

}
